package com.idriver.controller;

import com.idriver.bean.Admin;
import com.idriver.service.AdminService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String name = request.getParameter("userName");
        String password = request.getParameter("password");

        AdminService service = new AdminService();
        Admin admin = service.adminLoginService(new Admin(name, password));

        if (null != admin) {
            System.out.println("登录成功");
            HttpSession session = request.getSession();
            session.setAttribute("admin", admin);
            response.sendRedirect("main.jsp");
        } else {
            System.out.println("登录失败");
            request.setAttribute("error", "登录失败，用户名或密码错误！");
            RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
            dispatcher.forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
